<template>
  <view :class="!isEmpty ? 'padding-top-big' : ''">
    <!-- 01. 头部组件 -->
    <home-header
      ref="homeHeaderRef"
      :search-tip="searchTip"
      :search-auto="searchAuto"
      @search="search"
    />

    <!-- 空白页 -->
    <empty
      ref="emptyRef"
      v-if="isEmpty"
      e-style="round"
      e-type="search"
      tip="搜索数据为空"
      btn-tip="重新搜索"
      height="70vh"
      :auto="false"
      @goto="toSearch"
    />
    <view v-else>
      <!-- 筛选区 -->
      <view class="navbar pos-f w-full dflex bg-main" :style="headerPosition">
        <view
          class="nav-item dflex-c flex1 pos-r h-full"
          :class="{ active: filterIndex === 0 }"
          @click="navbarClick(0)"
        >
          综合排序
        </view>
        <view
          class="nav-item dflex-c flex1 pos-r h-full"
          :class="{ active: filterIndex === 1 }"
          @click="navbarClick(1)"
        >
          销量优先
        </view>
        <view
          class="nav-item dflex-c flex1 pos-r h-full"
          :class="{ active: filterIndex === 2 }"
          @click="navbarClick(2)"
        >
          <text>价格</text>
          <view class="">
            <view
              class="iconfont icon-jiantoushang ft-dark dflex-c"
              :class="{ active: priceOrder === 2 && filterIndex === 2 }"
            />
            <view
              class="iconfont icon-jiantouxia ft-dark dflex-c"
              :class="{ active: priceOrder === 1 && filterIndex === 2 }"
            />
          </view>
        </view>
      </view>

      <!-- 商品列表区 -->
      <view class="goods-list">
        <view class="list dflex-b dflex dflex-wrap-w w-full">
          <view
            class="item bg-main border-radius-sm padding-bottom-sm"
            v-for="(item, index) in goodsDatas"
            :key="index"
            @click="togoods(item)"
          >
            <view class="image-wrapper">
              <image mode="aspectFill" :lazy-load="true" :src="item.img" />
            </view>
            <text class="title clamp padding-sm">{{ item.name }}</text>
            <view class="padding-left-sm dflex-b">
              <text class="price">{{ item.price / 100 }}</text>
              <text class="ft-dark margin-right-sm fs-xs">已售 {{ item.sale_cnt }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 置顶 -->
    <totop ref="totopRef" />
  </view>
</template>
<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { onLoad, onPageScroll, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
  import HomeHeader from '@/components/tabbar/home-header.vue';
  import Empty from '@/components/empty/aster-empty.vue';
  import Totop from '@/components/totop/totop.vue';
  import config from '@/utils/config';
  import { url_params } from '@/utils';
  import { SortType, SortOrder, PAGE_SIZE, LoadType } from '@/enums/searchEnum';
  import { searchData } from '@/services/api/search/search';
  import { router } from '@/utils/router';

  // 查询列表是否为空
  const isEmpty = ref(true);
  // 商品
  const goodsDatas = ref([]);
  // 加载更多状态
  const loadType = ref(LoadType.MORE);
  // 查询条件
  const queryData = reactive({
    keywords: '',
    sortType: '',
    sortOrder: '',
    pageNum: 1,
    pageSize: PAGE_SIZE,
  });

  // 头部参数
  const homeHeaderRef = ref();
  // 直接查询
  const searchAuto = ref(!0);
  // 查询关键字
  const searchTip = ref('请输入搜索关键字');
  // 回调函数
  const search = () => {
    console.log('header search');
  };

  // 空白页
  const emptyRef = ref();
  // 置顶页
  const totopRef = ref();

  // 筛选区样式
  const headerPosition = ref(`position: 'fixed'`);
  // 0综合排序 1销量优先 2价格排序
  const filterIndex = ref(0);
  // 1价格从低到高 2价格从高到低
  const priceOrder = ref(0);

  // 监听页面加载，其参数为上个页面传递的数据，参数类型为Object（用于页面传参）
  onLoad((options) => {
    if (options?.keywords) {
      searchTip.value = options?.keywords;
      queryData.keywords = options?.keywords;
    }
  });

  // 监听页面滚动
  onPageScroll((e) => {
    // 兼容iOS端下拉时顶部漂移
    if (e.scrollTop >= 0) {
      headerPosition.value = "position: 'fixed'";
    } else {
      headerPosition.value = "position: 'absolute'";
    }
    // this.scrollTop = e.scrollTop
    totopRef.value.change(e.scrollTop);
  });

  // 监听用户下拉动作，一般用于下拉刷新
  onPullDownRefresh(() => {
    loadData('refresh');
  });

  // 页面滚动到底部的事件（不是scroll-view滚到底），常用于下拉下一页数据
  onReachBottom(() => {
    loadData('load');
  });

  /**
   * 筛选
   * @param index 0综合排序 1销量优先 2价格排序
   */
  const navbarClick = (index: number) => {
    if (filterIndex.value === index && index !== 2) {
      return;
    }

    filterIndex.value = index;

    if (index === 2) {
      priceOrder.value = priceOrder.value === 1 ? 2 : 1;
    } else {
      priceOrder.value = 0;
    }

    if (filterIndex.value == 0) {
      // 综合排序
      queryData.sortType = SortType.SORT;
      queryData.sortOrder = SortOrder.ASC;
    } else if (filterIndex.value == 1) {
      // 销量优先
      queryData.sortType = SortType.SALE;
      queryData.sortOrder = SortOrder.DESC;
    } else if (filterIndex.value == 2) {
      // 价格排序
      queryData.sortType = SortType.PRICE;
      if (priceOrder.value == 1) {
        // 降序
        queryData.sortOrder = 'desc';
      } else if (priceOrder.value == 2) {
        // 升序
        queryData.sortOrder = 'asc';
      }
    }

    uni.pageScrollTo({
      duration: 300,
      scrollTop: 0,
    });

    loadData('refresh');
    uni.showLoading({
      title: '正在加载',
    });
  };

  /**
   * 加载数据
   * @param type 类型,下拉刷新|上拉加载
   */
  const loadData = (type: string) => {
    if (loadType.value == LoadType.LOADING) {
      // 防止重复加载
      return;
    }

    if (type == 'refresh') {
      // 从首页开始加载
      queryData.pageNum = 1;
    }

    // 没有更多直接返回
    if (type === 'add') {
      if (loadType.value === LoadType.NOMORE) {
        return;
      }
      // 加载中
      loadType.value = LoadType.LOADING;
    } else {
      // 更多
      loadType.value = LoadType.MORE;
    }

    searchData().then(({ data }) => {
      // historyDatas.value = data.data;
    });
  };

  // 跳转搜索页
  const toSearch = () => {
    router.push(config.route.search);
  };

  // 跳转详情页
  const togoods = (goodsId: string) => {
    router.push(config.route.goods + url_params({ goodsId: goodsId }));
  };
</script>

<style lang="scss">
  .navbar {
    top: var(--window-top);
    left: 0;
    height: 100rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.06);
    z-index: 10;

    .nav-item {
      color: #303133;
      font-size: $uni-font-size-base + 2rpx;

      &.active {
        &:after {
          content: '';
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 120rpx;
          height: 0;
          border-bottom: 4rpx solid #d6d7d9;
        }
      }
    }

    .iconfont {
      width: 30rpx;
      height: 14rpx;
      font-size: 20rpx;
      line-height: 1;
      margin-left: 4rpx;
    }
  }

  .goods-list {
    .list {
      padding: 0 3vw 20rpx;
    }

    .item {
      width: 46vw;
      overflow: hidden;
      margin-top: 2vw;

      &:nth-child(2n) {
        margin-left: 1vw;
      }

      &:nth-child(2n + 1) {
        margin-right: 1vw;
      }
    }

    .image-wrapper {
      width: 100%;
      height: 300rpx;
      overflow: hidden;

      image {
        width: 100%;
        height: 100%;
        opacity: 1;
      }
    }
  }
</style>
